<?php
    
    namespace App\Models;

    use App\Consts\Tools\ToolsConsts;
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
    use App\Consts\TableConsts\TableConsts;
    use App\Service\NewContract\ContractService;
    use App\Models\Client\ClientModel;
    use App\Tools\File\ExcelFile;
	use App\Models\modelSystemOperationLog;
	use App\Service\Approval\PublicDingTalkApprovalService;
	use App\Consts\Approval\ApprovalSubmitTypeConsts;
	use App\Models\CreditProject\tModelCreditProjectDeparetmentReview;
	use App\Models\CreditProject\tModelCreditProjectVerify;
	use App\Models\CreditProject\tModelCreditQuota;
	use App\Models\CreditProject\tModelCustomerAllCreditProject;
	use App\Func\AgendaFunc;
	use App\Service\Approval\OldDingTalkApprovalService;

	/* adjust maximum default memory limit to avoid no enough memory to be used by php array
     *
     *
     *
     *
	 */
    ini_set('memory_limit', '256M');

    /* credit project manage
     * 
     * developer	: BREEZEER
     * date			: 2022.05.01
     * description	: credit project model
     *
     *
     *
     *
     *
     * 
     */
    class modelCreditProjectManage extends Model
    {
		# reference trait 
		#
		#
        use HasFactory																							;
		use tModelCreditProjectDeparetmentReview																;	# 内部审核和丁丁审核
		use tModelCreditProjectVerify								 											;	# 信用项目校验
		use tModelCreditQuota																					;	# 上下游客户的信用额度计算
		use tModelCustomerAllCreditProject																		;	# 上下游客户所有的信用项目分布情况

		# 信用项目的状态
		#
		#
		public const CREDIT_PROJECT_STATUS_1_WAIT_FOR_REVIEW												= 1;	# 等待审核
		public const CREDIT_PROJECT_STATUS_2_REVIEW_OK														= 2;	# 审核完成
		public const CREDIT_PROJECT_STATUS_3_CREDIT_MANAGER_REVIEW											= 3;	# 信控专员审查
		public const CREDIT_PROJECT_STATUS_4_FINANCE_MANAGER_REVIEW											= 4;	# 财务专员审查
		public const CREDIT_PROJECT_STATUS_5_REVIEWING														= 5;	# 审核中
		public const CREDIT_PROJECT_STATUS_6_REVIEW_REJECT													= 6;	# 审核不通过
		public const CREDIT_PROJECT_STATUS_7_AMOUNT_ADJUST_REVIEW											= 7;	# 调增调减审核中				
		public const CREDIT_PROJECT_STATUS_8_DEPARTMENT_LEADER_REVIEWING									= 8;	# 部门领导初步审查
		public const CREDIT_PROJECT_STATUS_9_FINANCE_MANAGER_REVIEW_COMPLETED								= 9;	# 财务专员审查已经完成
		public const CREDIT_PROJECT_STATUS_10_REVIEW_OK_BUT_CUSTOMER_NOT_ENOUGH_CREDIT_QUOTA				= 10;	# 审核完成但客户信用余额不足
		public const CREDIT_PROJECT_STATUS_20_HAVE_SEND_REQUEST_APPROVAL_REPORT_TO_DD						= 12;	# 已送钉钉审批
 

		# 信用项目的完成状态																						=> [ 1=没有完成 2=已经完成 【项目截止时间到了，项目账款回款完成】]
		#
		#
		public const CREDIT_PROJECT_COMPLETED_STATUS_1_NOT_COMPLETED										= 1;	# 没有完成
		public const CREDIT_PROJECT_COMPLETED_STATUS_2_COMPLETED											= 2;	# 已经完成

		# 预付/赊销																									=> [ 1预付特批 2赊销 ]
		#
		#
		public const CREDIT_PROJECT_SALE_TYPE_1_PREPAY_SPECIAL_ALLOW										= 1;	# 预付特批
		public const CREDIT_PROJECT_SALE_TYPE_2_CREDIT_SALE													= 2;	# 赊销
 
		# 信用项目调增调减的审批状态																				=> [1=等待批准 2=已经批准 3=审核不通过 4=审核成功后但回调验不能满足额度要求]
		#
		#
		public const CREDIT_PROJECT_ADJUST_QUOTA_REVIEW_1_WAIT_FOR_REVIEW									= 1;	# 等待批准
		public const CREDIT_PROJECT_ADJUST_QUOTA_REVIEW_2_REVIEW_OK											= 2;	# 已经批准
		public const CREDIT_PROJECT_ADJUST_QUOTA_REVIEW_3_REVIEW_REJECT										= 3;	# 审核不通过
		public const CREDIT_PROJECT_ADJUST_QUOTA_REVIEW_4_REVIEW_OK_BUT_CUSTOMER_NOT_ENOUGH_CREDIT_QUOTA	= 4;	# 审核成功后但回调验不能满足额度要求

        # model default initialization
        #
        #
        protected   $table																					= TableConsts::CY_CREDIT_PROJECT_EX_TABLE_NAME	;
        protected   $primaryKey																				= 'id'											;
        public		$timestamps																				= false											;
        public function getTableName()
        { 
            return $this->m_cHelper->gfGetTableName($this->table)																							; 
        }
        public function __construct	($p_controller=null)
        {	
            $this->m_cHelper																				= app()->gcHelper								;																												# global helper
			$this->m_p_controller																			= $p_controller									;
			$this->m_modelSystemOperationLog																= new modelSystemOperationLog ($this->m_cHelper->gfGetCurrentStaffInfo()->staff_id, modelSystemOperationLogConstCategory::LOG_TYPE_CREDIT_PROJECT)	;			# system operation log
        }

		/* 添加我的代办事项
		 *
		 */
		public function addSomethingToMyWorkbench($n_staff_id,$n_type,$n_source_id)
		{
			AgendaFunc::addAgenda($n_staff_id,$n_type,$n_source_id);
		}

        /* 导出信用项目数据
         *
         */
        public function exportCreditProjectDataToExcelFile()
        {
            $data           = request()->all();
            $ef             = new ExcelFile();
            $head           = [
                                'ID'                ,
                                '创建日期'          ,
                                '审批编号'          ,
                                '项目名称'          ,
                                '申请部门'          ,
                                '预付/赊销'         ,
                                '信用客户'          ,
                                '信用额度[元]'      ,
                                '额度使用截止日期'  ,
                                '业务经办人'        ,
                                '状态'              ,
                              ];

            # download file name
            #
            $filename = $data['exName'] ?? $this->m_cHelper->gfCreateUUID();
            
            # 
            #
            $this->m_cHelper->gfDbQuery()->select 
			(
                "
                    select 
                            *
                            ,(select department_name	from ".$this->m_cHelper->gfGetTableName(TableConsts::CY_DEPARTMENT_TABLE_NAME)	." where department_id=a.credit_project_business_department_id)				                    as department_name
                            ,(select client_name		from ".$this->m_cHelper->gfGetTableName(TableConsts::CY_CLIENT_BASIC_TABLE_NAME)." where client_id=a.credit_project_client_id)								                    as client_name 
                            ,(
                                select 
                                    delay_date_end		
                                from 
                                    ".$this->m_cHelper->gfGetTableNameByConstKey('CY_DELAY_DATE_TABLE_NAME')."	
                                where 
                                    pid		= a.id 
                                    and id	= (select ifnull(max(id),0) from ".$this->m_cHelper->gfGetTableNameByConstKey('CY_DELAY_DATE_TABLE_NAME')." where pid=a.id)
                            )																																														                    as credit_project_quota_date
                            ,(select staff_name			from ".$this->m_cHelper->gfGetTableName(TableConsts::CY_STAFF_TABLE_NAME)		." where staff_id=a.credit_project_business_staff_id)						                    as credit_project_business_staff_name
                            ,(select staff_name			from ".$this->m_cHelper->gfGetTableName(TableConsts::CY_STAFF_TABLE_NAME)		." where staff_id=a.credit_project_agent_staff_id)							                    as credit_project_agent_staff_name
                            ,(select dictionary_name    from ".$this->m_cHelper->gfGetTableNameByConstKey('CY_DATA_DICTIONARY_TABLE_NAME')." as b  where b.parent_id = 152  and b.dictionary_value=a.credit_project_status)             as credit_project_status_name
                            ,(select dictionary_name    from ".$this->m_cHelper->gfGetTableNameByConstKey('CY_DATA_DICTIONARY_TABLE_NAME')." as b  where b.parent_id = 49   and b.dictionary_value=a.credit_project_prepaid_sale_type)  as credit_project_prepaid_sale_type_name
                    from 
                            ".$this->m_cHelper->gfGetTableNameByConstKey('CY_CREDIT_PROJECT_EX_TABLE_NAME')."																										                    as a
                    where 
                            status	= 1
                    order by a.id desc
                "
            )
			->forEachRow	
			(
				function($row)
				{
					return	[
									'id'				                        => $row->id                         						,	# id
									'create_at'				                    => $row->create_at                         					,	#
									'credit_project_approve_code'				=> $row->credit_project_approve_code						,	# 审批编号
									'credit_project_name'						=> $row->credit_project_name								,	# 项目名称
									'credit_project_business_department_name'	=> $row->department_name									,	# 申请部门
									'credit_project_prepaid_sale_type_name'     => $row->credit_project_prepaid_sale_type_name              ,	# 预付/赊销 1预付特批 2赊销
									'credit_project_client_name'				=> $row->client_name										,	# 客户名称	
									'credit_project_quota'						=> $row->credit_project_quota								,	# 信用额度
									'credit_project_quota_date'					=> $row->credit_project_quota_date							,	# 额度使用截止日期
									'credit_project_agent_staff_name'			=> $row->credit_project_agent_staff_name					,	# 经办人
									'credit_project_status_name'                => $row->credit_project_status_name							,	# 状态
							];
				}
				,
				$data
			);
            
			# add system operation log
			#
			$this->m_modelSystemOperationLog->addSystemOperationLog('导出信用项目数据');

            #
            #
            return  [
                        "filename" => $ef->fileAllExport($head,$data['content'],'',$filename)
                    ];
        }
 
        /* 信用客户基本信息 【 正常情况下每年会产生一次信用评级，所以信用客户可能会有多条记录，提取唯一标识： credit_client_status=1 】
         *
         */
        private function getCreditCustomerInformation($n_client_id/* client id */)
        {
            return $this->m_cHelper->gfDbQuery()->getDbOneRow("select * from ".$this->m_cHelper->gfGetTableNameByConstKey('CY_CREDIT_CLIENT_TABLE_NAME')." where credit_client_status=1/* 正常 */ and client_id=?"	,[$n_client_id]);
        }

        /* 获取客户类型	=>  1=客户【下游 => 贸易类型 】 , 2=供应商【上游 => 生产类型 】
         *
         */
        private function getCreditCustomerType($n_client_id/* client id */)
        {
            return $this->m_cHelper->gfDbQuery()->getDbValue("select client_counterparty_type from ".$this->m_cHelper->gfGetTableNameByConstKey('CY_CLIENT_BASIC_TABLE_NAME')." where status=1 and client_id=?",[$n_client_id]);
        }
                                                
        /* 下游客户赊销项目对应合同履约完成		____
         *											\
         *											 >	修改信用项目完成状态为 => 2=已经完成【 这个状态与信用项目截止日期没有什么必然的关联，该字段仅仅标识当前信用项目的一种完成状态 （信用项目的完成状态：1=没有完成 2=已经完成【项目截止时间到了，项目账款回款完成】）】
         * 上游客户预付特批合同履约完成			____/
         *
         *
         *
         *
         *
         *
         */
        public function setCreditProjectCompletedSuccess($credit_project_id)
		{
            if($this->verifyCreditProjectIdExist($credit_project_id)->status)
            {
                # update [cy_credit_project_ex.credit_project_completed_status = 2] => 2=已经完成【 项目截止时间到了项目账款回款完成 】
                #
                $this->m_cHelper->gfDbQuery()->update( "update ".$this->m_cHelper->gfGetTableNameByConstKey('CY_CREDIT_PROJECT_EX_TABLE_NAME')." set credit_project_completed_status=2/* 2=已经完成 */ where id=?",[$credit_project_id]);

                #
                #
                return true;
            }
        }

        /* 获取信用项目的确认事项
         *
         */
        public function getCreditProjectConfirm(int $client_id/* 信用客户 */,int $department_id/* 部门 */)
        {
            # 信用客户( $client_id )的相关信息
            #
            #
            {
                $credit_client						= $this->m_cHelper->gfDbQuery()->getDbOneRow("select * from ".$this->m_cHelper->gfGetTableNameByConstKey('CY_CREDIT_CLIENT_TABLE_NAME')." where status=1 and credit_client_status=1/* 正常 */ and client_id=?",array($client_id));
                $ar									= $this->getCreditClientRemainAmount($client_id);
                $credit_client_approval_quota		= $ar['credit_client_approval_quota']			; # 信用客户已批准信用额度
                $credit_client_quota_prepaid		= $ar['credit_client_quota_prepaid'	]			; # 信用客户预付额度
                $credit_client_quota_sale			= $ar['credit_client_quota_sale'	]			; # 信用客户赊销额度
            }

            # 业务部门( $department_id )预算额度包括计算获取【 1.最大预算额度 2.现在的余额 】
            # 
            # 
            # date	: 2022/6/10
            #
            #	1. 公司和部门的额度已经不再计算，全部为 0
            #
            #
            #
            {
                $department_quota_max_count			= 0												;	# 部门最大额度  = 0
                $department_quota_remainder_count	= 0												;	# 部门余额		= 0 
            }

            # 信用客户正在进行当中的所有信用项目列表 
            #
            $credit_project_current_project_list	= $this->getCreditClientAllProject($client_id);
            
            #
            #
            return 	[
                        'is_ignore_credit_customer'					=> @$credit_client['is_ignore_credit_customer']								,
                        'credit_client_level'						=> @$credit_client['credit_client_level']									,
                        'credit_client_quota_max'					=> @$credit_client['credit_client_quota_max']								,
                        'credit_client_approval_quota'				=> $credit_client_approval_quota											,
                        'credit_client_quota_prepaid'				=> $credit_client_quota_prepaid												,
                        'credit_client_quota_sale'					=> $credit_client_quota_sale												,
                        'credit_project_client_id'					=> $client_id																,
                        'department_quota_max_count'				=> $department_quota_max_count											    ,
                        'department_quota_remainder_count'			=> $department_quota_remainder_count										,
                        'credit_project_business_department_id'		=> $department_id															,
                        'credit_project_current_project_list'		=> @$credit_project_current_project_list['content']							,
                    ];
        }
		
		public function getCreditProjectTableRawInformationByID($credit_project_id)
		{
			$ooo		= [];if($this->verifyCreditProjectIdExistEx($credit_project_id,$error)===true)
			{
				$ooo	= $this->m_cHelper->gfDbQuery()->getDbOneRow("select * from ".$this->m_cHelper->gfGetTableNameByConstKey('CY_CREDIT_PROJECT_EX_TABLE_NAME') ." where status=1 and id=?",[$credit_project_id]);
			}

			return $this->m_cHelper->toObjectEx($ooo);
		}

		/* modfiy credit project 
		 *
		 */
        public function creditProjectModify($j,$credit_project_id/* 信用项目id */)
        {
            # 信用项目id ok?
            #
            if($this->verifyCreditProjectIdExistEx($credit_project_id,$ce)===false)
            {
                return $this->m_cHelper->gfApiEchoExHttpException($ce->message,"creditProjectModify.100");
            }

			# 客户的信用项目能够创建或者修改吗
			#
			if($this->verfiyCreditProjectCanBeAddOrModify($j->credit_project_client_id)===false)
			{
				return $this->m_cHelper->gfApiEchoExHttpException("您的信用项目暂时无法新增或者修改,请稍后重试",'creditProjectModify.104');
			}		
            
            # 检查当前信用项目的状态确认是否可以被修改
            #
            $cbm = $this->verifyCreditProjectCanBeModify($credit_project_id);if($cbm->b_can_be_modify==true||$cbm->b_can_be_modfiy_part==true)
            {
            }
            else
            {
                return $this->m_cHelper->gfApiEchoExHttpException($cbm->message,'creditProjectModify.101');
            }

            # 客户类型和项目类型是否匹配
            #
            if($this->verifyClientTypeAndCreditProjectPrepaidSaleTypeOk($j->credit_project_client_id/* client id */,$j->credit_project_prepaid_sale_type/* 预付/赊销 1预付特批 2赊销 */))
            {
            }
            else
            {
                return $this->m_cHelper->gfApiEchoExHttpException("信用客户id: ".$j->credit_project_client_id." 的客户类型与信用项目id: [".$credit_project_id."]的预付/赊销类型【".$j->credit_project_prepaid_sale_type." => 预付/赊销 1预付特批 2赊销】不匹配","creditProjectModify.102");
            }

			# 信用项目额度必须大于零
            #
            if($this->m_cHelper->gfIsNumeric($j->credit_project_quota) === false || $j->credit_project_quota <= 0 )
            {
				return $this->m_cHelper->gfApiEchoExHttpException("信用项目额度必须大于零",'creditProjectModify.105');
			}

            # 客户的信用余额够吗 => 这里仅仅对下游客户的赊销进行限定预付特批不验证客户的信用余额
            #
            if($j->credit_project_prepaid_sale_type == self::CREDIT_PROJECT_SALE_TYPE_2_CREDIT_SALE /* 2=赊销 */) 
            {
                if($this->verifyClientHaveEnoughRemainCreditAmount($j->credit_project_client_id/* client id */,$j->credit_project_quota/* 准备申请的额度 */)) 
                {
                }
                else
                {
                    return $this->m_cHelper->gfApiEchoExHttpException("信用客户id: ".$j->credit_project_client_id." 信用余额不足，请重新调整申请额度",'creditProjectModify.103');
                }
            }
            
            # get credit project id
            #
            $credit_project_id	= $this->m_cHelper->gfGetIntValue($credit_project_id);
            $id					= $credit_project_id;

            #  修改信用项目的基本信息 
            #
            $this->m_cHelper->gfDbQuery()->updateByArrayWithWhere
			(
                    $this->getTableName()
                    ,
                    ["where id=? and owner_id=?",[$id,$this->m_cHelper->gfGetCurrentStaffInfo()->staff_id]]
                    ,
                    [
                            "credit_project_approve_code"						=> $j->credit_project_approve_code						,
                            "credit_project_business_department_id"				=> $j->credit_project_business_department_id			,  
                            "credit_project_business_staff_id"     				=> $j->credit_project_business_staff_id					, 
                            "credit_project_agent_staff_id"						=> $j->credit_project_agent_staff_id					,
                            "credit_project_client_id"             				=> $j->credit_project_client_id							,
                            "credit_project_name"								=> $j->credit_project_name								,
                            "credit_project_quota"								=> $j->credit_project_quota								,
                            "credit_project_prepaid_sale_type"					=> $j->credit_project_prepaid_sale_type					,
                            "credit_project_apply_date"							=> $this->m_cHelper->gfGetCurrentLocalDate()			,
                            "is_important_credit_project"						=> $j->is_important_credit_project						,

                            # 业务版块
                            #
                            "credit_project_business_plate"						=> $j->credit_project_business_plate					,

							# 业务模式 
                            #
                            "credit_project_business_model_type"				=> $j->credit_project_business_model_type				,						
                            
							# 信用项目的确认事项之财务信息确认 (当申请被提交审查，需要保存财务确认信息到这来）tips:json
							#
							"credit_project_confirm_information_for_finance"	=> $this->m_cHelper->gfJsonEncode($this->m_cHelper->gfJsonDecode($j->credit_project_confirm_information_for_finance/* json */)->getAllJsonData())	,

							# 文件上传对象返回的是一个数组对象
                            #
                            # tips :
                            #			1. 文件 json 格式
                            #				1.0 单文件 => "[{\"file_id\":9}]"
                            #				1.0 多文件 => "[{\"file_id\":10},{\"file_id\":11}]"
                            #
                            #			2. 调用 $this->m_cHelper->gfGetcFile()->getUploadFilesIds => 从中提取file_id
                            #
                            #
                            #
                            "investigation_report_files"						=> $this->m_cHelper->gfGetcFile()->getUploadFilesIds(is_array($j->investigation_report_files)	? $j->investigation_report_files	:[])			,
                            "analysis_report_files"								=> $this->m_cHelper->gfGetcFile()->getUploadFilesIds(is_array($j->analysis_report_files)		? $j->analysis_report_files			:[])			,
                            "other_files"										=> $this->m_cHelper->gfGetcFile()->getUploadFilesIds(is_array($j->other_files)					? $j->other_files					:[])			,
							
							# 由于多步骤审核已经整合到一步,所以信用项目完成内容修改即可进入待提交审查阶段 [ 此时 Cy_credit_project_ex.credit_project_status => 9=财务专员审查成功 ]
							#
							"credit_project_status"								=> self::CREDIT_PROJECT_STATUS_9_FINANCE_MANAGER_REVIEW_COMPLETED																					, # 财务专员审查已经完成
							
							# 信用项目完整的丁丁审查表单数据
							#
							'review_web_form_for_credit_project'				=> $this->m_cHelper->gfJsonEncode	(
																														[
																															'data_for_raw'		=> $this->m_cHelper->gfJsonDecode($j->review_web_form_for_credit_project/* json */)->getAllJsonData()
																															,
																															'data_for_dingding'	=> []
																														]
																													),
                    ]
            );

			# add system operation log
			#
			$this->m_modelSystemOperationLog->addSystemOperationLog('修改信用项目信息',$id,$j->getOriginJsonString());

			//            # 获取部门和客户的确认信息然后更新保存在字段 => cy_credit_project_ex.credit_project_confirm_information
			//            #
			//            $credit_project_confirm_information_json							= $this->m_cHelper->gfJsonEncode($this->getCreditProjectConfirm($j->credit_project_client_id/* client id */,$j->credit_project_business_department_id /* department id */));$this->m_cHelper->gfDbQuery()->update
			//			(
			//				"
			//                    update 
			//                            ".$this->getTableName()." 
			//                    set 
			//                            credit_project_confirm_information	= ? 
			//                    where 
			//                            id									= ? 
			//                            and owner_id						= ?
			//                "
			//                ,
			//				[$credit_project_confirm_information_json,$id,$this->m_cHelper->gfGetCurrentStaffInfo()->staff_id]
			//            );

			//			# add system operation log
			//			#
			//			$this->m_modelSystemOperationLog->addSystemOperationLog('获取部门和客户的确认信息然后更新保存信息',$id,$credit_project_confirm_information_json);

            #
            #
            return $this->getCreditProjectBaseInformation($id/* credit project id */);
        }
        
        /* 添加信用项目
         * 
         */
        public function creditProjectAdd($j,$h)
		{
            # 检查当前职员是否存在
            #
            if($this->m_cHelper->gfDbQuery()->getDbValue("select staff_id from ".$this->m_cHelper->gfGetTableNameByConstKey('CY_STAFF_TABLE_NAME')." where staff_id=?",[$h->gfGetCurrentStaffInfo()->staff_id])>0)
			{
			}
			else
			{
                return $this->m_cHelper->gfApiEchoExHttpException("客户: ".$h->gfGetCurrentStaffInfo()->staff_id." 不存在","creditProjectAdd.100");
            }

			# 信用客户评审信息存在吗
			#
			if($this->verifyCreditClientOk($j->credit_project_client_id)===false)
			{
                return $this->m_cHelper->gfApiEchoExHttpException("客户: ".$j->credit_project_client_id." 信用客户评审信息不存在","creditProjectAdd.100.1");
			}

			# 客户的信用项目能够创建或者修改吗
			#
			if($this->verfiyCreditProjectCanBeAddOrModify($j->credit_project_client_id)===false)
			{
				return $this->m_cHelper->gfApiEchoExHttpException("您的信用项目暂时无法新增或者修改,请稍后重试",'creditProjectAdd.100.2');
			}

            # 客户类型和项目类型是否匹配
            #
            if($this->verifyClientTypeAndCreditProjectPrepaidSaleTypeOk($j->credit_project_client_id/* client id */,$j->credit_project_prepaid_sale_type/* 预付/赊销 1预付特批 2赊销 */)) 
			{
			}
			else
			{
                return $this->m_cHelper->gfApiEchoExHttpException("信用客户id: ".$j->credit_project_client_id."的客户类型与信用项目的预付/赊销类型【".$j->credit_project_prepaid_sale_type." => 预付/赊销 1预付特批 2赊销】 不匹配","creditProjectAdd.101");
            }

            # 默认业务板块数据填充 
            #
            $credit_project_business_plate_default = '{"radioList":[{"title":"钢铁","childList":[]},{"title":"铁建","childList":["钢铁","水泥"]},{"title":"矿产","childList":[]},{"title":"能源","childList":[]},{"title":"油品","childList":[]},{"title":"国际","childList":[]}],"currentVal":"","currentSubVal":""}';

            # add 
            #
            $id	= $h->gfDbQuery()->insertByArray
			(
                    $this->m_cHelper->gfGetTableNameByConstKey('CY_CREDIT_PROJECT_EX_TABLE_NAME')
                    ,
					[
                            # 自动产生审批编号
                            #
                            "credit_project_approve_code"			=> $this->m_p_controller->createUUIDForCreditProjectSN(),
                            
                            #
                            #
                            "credit_project_business_department_id" => $j->credit_project_business_department_id?? 0		,  
                            "credit_project_business_staff_id"     	=> $j->credit_project_business_staff_id		?? 0		, 
                            "credit_project_agent_staff_id"        	=> $j->credit_project_agent_staff_id					,
                            "credit_project_client_id"             	=> $j->credit_project_client_id				?? 0		,
                            "credit_project_name"					=> $j->credit_project_name								,
                            "credit_project_quota"					=> $j->credit_project_quota					?? 0		,
                            "credit_project_prepaid_sale_type"		=> $j->credit_project_prepaid_sale_type					,
                            "credit_project_apply_date"				=> $h->gfGetCurrentLocalDate()							,
                            "is_important_credit_project"			=> $j->is_important_credit_project			?? 2		,

                            # 业务模式 model_type,model_value  
                            #
                            "credit_project_business_model_type"	=> $j->credit_project_business_model_type				, 

                            # 文件上传对象返回的是一个数组对象
                            #
                            # tips :
                            #			1. 文件 json 格式
                            #				1.0 单文件 => "[{\"file_id\":9}]"
                            #				1.0 多文件 => "[{\"file_id\":10},{\"file_id\":11}]"
                            #
                            #			2. 调用 $this->m_cHelper->gfGetcFile()->getUploadFilesIds => 从中提取file_id
                            #
                            #
                            "investigation_report_files"			=> $this->m_cHelper->gfGetcFile()->getUploadFilesIds(json_decode($this->m_cHelper->gfIsEmptyString($j->investigation_report_files)	?'[]':$j->investigation_report_files	,true))	,
                            "investigation_report_files"			=> $this->m_cHelper->gfGetcFile()->getUploadFilesIds(json_decode($this->m_cHelper->gfIsEmptyString($j->analysis_report_files)		?'[]':$j->analysis_report_files			,true))	,
                            "investigation_report_files"			=> $this->m_cHelper->gfGetcFile()->getUploadFilesIds(json_decode($this->m_cHelper->gfIsEmptyString($j->other_files)					?'[]':$j->other_files					,true))	,

                            # 如果前端没有提交业务板块数据为空 => 从数据库字典表获取默认业务板块数据填充
                            #
                            "credit_project_business_plate"			=> $this->m_cHelper->gfIsEmptyString($j->credit_project_business_plate)?$credit_project_business_plate_default:$j->credit_project_business_plate									,
                            
                            # 本条记录的宿主即是后台登录职员的id
                            #
                            "owner_id"								=> $h->gfGetCurrentStaffInfo()->staff_id																																			,	
                    ]
            )->getLastInsertId();

			# insert ok ?
			#
			if( $id >0 )
			{
			}
			else
			{
				return $this->m_cHelper->gfApiEchoExHttpException("添加信用项目失败","creditProjectAdd.102");
			}

            # 在延期表【delay_date】添加一条记录
            #
            #						   ______ 未延期	=> 延期表只会有一条记录
            #						  /
            # 客户可能会延期截止日期 <
            #						  \______ 已延期	=> 延期表会有多条记录，按照 id 倒序排列取第一条记录就是客户目前最新的额度使用截止日期
            #
            #
            $h->gfDbQuery()->insertByArray
			(
                $h->gfGetTableName(TableConsts::CY_DELAY_DATE_TABLE_NAME)
                ,
				[
                    'delay_date_start'	=> $h->gfGetCurrentLocalDate()																			,
                    'delay_date_end'	=> $this->m_cHelper->gfGetCurrentLocalDateAdjustByYear($this->m_cHelper->gfGetCurrentLocalDate(),1)		, # 额度使用截止日期 【添加默认值 => 当前日期自动延期1年，这个值在预付合同绑定信用项目的时候，会修改这个延期时间】	
                    'delay_type'		=> ToolsConsts::CREDIT_PROJECT_DELAY																	, # 信用项目延期
                    'pid'				=> $id																									, # 主表 cy_credit_project_ex 的id	
                    "owner_id"			=> $h->gfGetCurrentStaffInfo()->staff_id																,  
                ]
            );

			//            # 获取部门和客户的确认信息然后更新保存在字段 => cy_credit_project_ex.credit_project_confirm_information
			//            #
			//            $credit_project_confirm_information_json = $this->m_cHelper->gfJsonEncode($this->getCreditProjectConfirm($j->credit_project_client_id??0/* client id */,$j->credit_project_business_department_id??0/* department id */));$this->m_cHelper->gfDbQuery()->update
			//			(
			//				"
			//					update 
			//							".$this->getTableName()." 
			//					set 
			//							credit_project_confirm_information	= ? 
			//					where 
			//							id									= ? 
			//							and owner_id						= ?
			//                "
			//                ,
			//				[$credit_project_confirm_information_json,$id,$this->m_cHelper->gfGetCurrentStaffInfo()->staff_id]
			//            );

			# add system operation log
			#
			$this->m_modelSystemOperationLog->addSystemOperationLog('添加信用项目',$id,$j->getOriginJsonString());

            #
            #
            return $this->getCreditProjectBaseInformation($id/* credit project id */);
        }
        private function getCreditProjectBaseInformation($credit_project_id){
            
            $h = $this->m_cHelper;$this->m_cHelper->gfDbQuery()->select("select * from ".$this->getTableName()." where id=?",array($credit_project_id),debug:false)->forEachRow
			(
				function($row) use ($h)
				{
					# 实地考察报告附件
					#
					$investigation_report_files			= @$h->gfGetUploadFileInfo(array($row->investigation_report_files));

					# 信用业务分析报告文件上传 
					#
					$analysis_report_files				= @$h->gfGetUploadFileInfo(array($row->analysis_report_files));

					# 其他附件
					#
					$other_files						= @$h->gfGetUploadFileInfo(explode(',',$row->other_files));

					# 业务模式
					#
					$credit_project_business_model_type = $row->credit_project_business_model_type;

					# 部门所在的公司id和公司名字
					#
					$company_id							= $h->gfDbQuery()->getDbValue("select company_id	from ".$h->gfGetTableName(TableConsts::CY_DEPARTMENT_TABLE_NAME)." where department_id	=?"	,array($row->credit_project_business_department_id));
					$company_name						= $h->gfDbQuery()->getDbValue("select company_name	from ".$h->gfGetTableName(TableConsts::CY_COMPANY_TABLE_NAME)	." where company_id		=?"	,array($company_id));

					#
					#
					return $row->removeItem(
												[
												]
					)->appendItem(array(

							'investigation_report_files'						=> $investigation_report_files					,
							'analysis_report_files'								=> $analysis_report_files						,
							'other_files'										=> $other_files									,
							'credit_project_business_model_type'				=> $credit_project_business_model_type			,
					))->appendItem(array(
							
							'credit_project_company_id'							=> $company_id									,
							'credit_project_company_name'						=> $company_name								,
							'credit_project_department_id'						=> $row->credit_project_business_department_id	,
							'credit_project_business_department_name'			=> $h->gfDbQuery()->getDbValue("select department_name		from ".$h->gfGetTableName(TableConsts::CY_DEPARTMENT_TABLE_NAME)."		where department_id=?"	,array($row->credit_project_business_department_id)),
							'credit_project_business_staff_name'				=> $h->gfDbQuery()->getDbValue("select staff_name			from ".$h->gfGetTableName(TableConsts::CY_STAFF_TABLE_NAME)."			where staff_id=?"		,array($row->credit_project_business_staff_id))		,
							'credit_project_agent_staff_name'					=> $h->gfDbQuery()->getDbValue("select staff_name			from ".$h->gfGetTableName(TableConsts::CY_STAFF_TABLE_NAME)."			where staff_id=?"		,array($row->credit_project_agent_staff_id))		,
					))->appendItem(array(

							'credit_project_quota_date'							=> $h->gfDbQuery()->getDbValue	(	"
																														select 
																																delay_date_end 
																														from 
																																".$this->m_cHelper->gfGetTableNameByConstKey('CY_DELAY_DATE_TABLE_NAME') ."
																														where 
																																pid		= ?
																																and id	= (select ifnull(max(id),0) from ".$this->m_cHelper->gfGetTableNameByConstKey('CY_DELAY_DATE_TABLE_NAME')." where pid = ?)
																													"
																													,
																													[$row->id,$row->id]
																												),
					))
					->appendItem (
									[
										'key'												=> $row->id																																																		,
										'credit_project_client_name'						=> $h->gfDbQuery()->getDbValue("select client_name			from ".$h->gfGetTableName(TableConsts::CY_CLIENT_BASIC_TABLE_NAME)."	where client_id=?"		,array($row->credit_project_client_id))				,
										'credit_project_client_type'						=> $h->gfDbQuery()->getDbValue("select credit_client_type	from ".$h->gfGetTableName(TableConsts::CY_CREDIT_CLIENT_TABLE_NAM)."	where client_id=?"		,array($row->credit_project_client_id))				,

										# 信用项目的确认事项之财务信息确认
										#
										'credit_project_confirm_information_for_finance'	=>	(
																									$row->credit_project_confirm_information_for_finance==null
																									?''
																									:$this->m_cHelper->gfJsonDecode($row->credit_project_confirm_information_for_finance)->getAllJsonData()
																								),
										# 信用项目完整的丁丁审查表单数据
										#
										'review_web_form_for_credit_project'				=>	(
																									$row->review_web_form_for_credit_project==null
																									? ''
																									: $this->m_cHelper->gfJsonDecode($row->review_web_form_for_credit_project)->data_for_raw
																								),

										# 信用项目的调增调减内部审批
										#
										'adjust_credit_project_quota_review_detail'			=>	[
																									'review_adjust_quota_step_1'		=> '', # $this->m_cHelper->gfJsonDecode($row->review_adjust_quota_step_1)->review_content	??'',	
																									'review_adjust_quota_step_2'		=> '', # $this->m_cHelper->gfJsonDecode($row->review_adjust_quota_step_2)->review_content	??'',	
																									'review_adjust_quota_step_3'		=> '', # $this->m_cHelper->gfJsonDecode($row->review_adjust_quota_step_3)->review_content	??'',	
																									'review_adjust_quota_step_4'		=> '', # $this->m_cHelper->gfJsonDecode($row->review_adjust_quota_step_4)->review_content	??'',	
																									'review_adjust_quota_step_5'		=> '', # $this->m_cHelper->gfJsonDecode($row->review_adjust_quota_step_5)->review_content	??'',	
																									'review_adjust_quota_step_6'		=> '', # $this->m_cHelper->gfJsonDecode($row->review_adjust_quota_step_6)->review_content	??'',	
																									'review_adjust_quota_step_status'	=> 1 , # $row->review_adjust_quota_step_status												,	
																								],
									]
								)->getOneRowAllData();
				}
				,
				$arx
			);	

            return $arx['content'];
        }

        /* 获取一个信用项目的详细资料
         *
         */
        public function creditProjectGetDetail($credit_project_id){

            # 获取项目的基本信息
            #
            $project_base_info												= $this->getCreditProjectBaseInformation($credit_project_id)[0];
     
            # 获取信用项目的确认事项
            #
            $project_confirm_info											= $this->m_cHelper->gfJsonDecode($project_base_info['credit_project_confirm_information'])->getAllJsonData();
        
            # 获取信用项目的的所有调整调减明细
            #
            $credit_project_adjust_credit_quota_detail						= $this->getCreditProjectAllAdjustQuotaList($credit_project_id)['credit_project_adjust_credit_quota_detail']; 

			# 获取信用项目额度使用分配情况
			#
			$credit_project_quota_usage_allocation_status					= $this->getCreditProjectQuotaUsageAllocationStatus($credit_project_id);
			
			# 获取操作日志
			#
			$system_operation_log											= $this->m_modelSystemOperationLog->getSystemOperationLog($credit_project_id);

			# 获取审批日志													=> 信用项目
			#
			$approval_log_project											= (new OldDingTalkApprovalService())->getApprovalLogBySourceIdSourceType($credit_project_id,ApprovalSubmitTypeConsts::SUBMIT_CREDIT_PROJECT_CREDIT_DEPARTMENT_LEADER_REVIEW);

            #
            #
            return	[
						'project_base_info'									=> $project_base_info								,	# 获取项目的基本信息
						'project_confirm_info'								=> $project_confirm_info							,	# 获取信用项目的确认事项
						'credit_project_adjust_credit_quota_detail'			=> $credit_project_adjust_credit_quota_detail		,	# 获取信用项目的的所有调整调减明细
						'credit_project_quota_usage_allocation_status'		=> $credit_project_quota_usage_allocation_status	,	# 获取信用项目额度使用分配情况
						'system_operation_log'								=> $system_operation_log							,	# 获取操作日志
						'approval_log_project'								=> $approval_log_project							,	# 获取审批日志
					];
        }

        /* 获取当前信用项目id下的所有调整调减明细
         *
         */
        private function getCreditProjectAllAdjustQuotaList($credit_project_id)
        {
            # 信用项目ok ?
            #
            if($this->verifyCreditProjectIdExistEx($credit_project_id)===false)
            {
                return $this->m_cHelper->gfApiEchoExHttpException("信用项目: ".$credit_project_id." 不存在","getCreditProjectAllAdjustQuotaList.100");	# panic => fatal error
            }

			#
			#
			$credit_project_information = $this->getCreditProjectTableRawInformationByID($credit_project_id);
            $ar							= [];
			$this->m_cHelper->gfDbQuery()->select("select * from ".$this->m_cHelper->gfGetTableNameByConstKey('CY_CREDIT_PROJECT_EX_ADJUST_QUOTA_TABLE_NAME')." where credit_project_id=? order by id desc ",[$credit_project_id],debug:false)->forEachRow
			(
				function($row) use($credit_project_information)
				{
						return $row->appendItem	(
													[
														'key'						=> $row->id											,
														'credit_project_name'		=> $credit_project_information->credit_project_name	,
													]
												)->getOneRowAllData();
                }
                ,
                $ar
            );

            return ['credit_project_adjust_credit_quota_detail' => $ar['content']];
        }


        /* 获取信用项目列表默认是全部台账带分页功能
         *
         */
        public function creditProjectList($j){

            # build standard where condition SQL
            #
            #
            {
                $filters					= $this->m_cHelper->gfJsonDecode($j->filters)->getAllJsonDataToObject();
                $build_sql_where_for_search	= $this->m_cHelper->gfDbQuery()->buildSqlWhereWithConditionsAndValue();

                # 通过信用项目名称过滤
                #
                if(@$filters->credit_project_name != '' /* 模糊查询信用项目名称 */)
                {
                    $this->m_cHelper->gfDbQuery()->select("select id from ".$this->m_cHelper->gfGetTableNameByConstKey('CY_CREDIT_PROJECT_EX_TABLE_NAME')." force index(credit_project_name) where credit_project_name like ?",["%".$filters->credit_project_name."%"])->forEachRow
					(
						function($row)
						{
							return $row->id;
						}
						,
						$ar_credit_project_id
					);

                    #
                    #
                    if(count($ar_credit_project_id['content']) > 0)
                    {
                        $build_sql_where_for_search->appendWhereFilterContidion (" and a.id in (".implode(',',$ar_credit_project_id['content']).") and 1=?"	,1);
                    }
                    else
                    {
                        $build_sql_where_for_search->appendWhereFilterContidion (" and 1=?"																	,0);
                    }					
                }

                # 通过部门id过滤
                #
                if(@$filters->credit_project_business_department_id	==''	){}else{$build_sql_where_for_search->appendWhereFilterContidion(' and credit_project_business_department_id	= ?'	,$filters->credit_project_business_department_id)	;}

                # 通过信用项目类型过滤
                #
                if(@$filters->credit_project_type					==''	){}else{$build_sql_where_for_search->appendWhereFilterContidion(' and credit_project_prepaid_sale_type		= ?'	,$filters->credit_project_type)						;}

                # 通过客户id过滤
                #
                if(@$filters->client_id								==''	){}else{$build_sql_where_for_search->appendWhereFilterContidion(' and credit_project_client_id				= ?'	,$filters->client_id)								;}
            
                # 通过信用项目状态过滤
                #
                if(@$filters->credit_project_status					==''	){}else{$build_sql_where_for_search->appendWhereFilterContidion(' and credit_project_status					= ?'	,$filters->credit_project_status)					;}

                # 通过信用项目预付/赊销
                #
                if(@$filters->credit_project_prepaid_sale_type		==''	){}else{$build_sql_where_for_search->appendWhereFilterContidion(' and credit_project_prepaid_sale_type		= ?'	,$filters->credit_project_prepaid_sale_type)		;}

				# 绑定合同到信用项目
				#
				if(@$filters->bind_contract_to_credit_project		==''	)
				{
				}
				else
				{
					# 查询合同已经绑定过的信用项目id
					#
					$this->m_cHelper->gfDbQuery()->select
					(
						"select 
								credit_project_id 
						from 
								".$this->m_cHelper->gfGetTableNameByConstKey('CY_CONTRACT_TABLE_NAME')." 
						where 
								1						=	1
								and credit_project_id	>	0												/* 已经绑定的信用项目id		*/
								and status				=	1												/* 合同状态 1正常 2已删除	*/
								and contract_status	   !=	15												/* 合同没有被废弃			*/
						"
					)
					->forEachRow
					(
						function($row)
						{
							return $row->credit_project_id;
						}
						,
						$ar_all_binded_credit_project_id
					);
					$ar_all_binded_credit_project_id_ex = [-1];if(count($ar_all_binded_credit_project_id['content'])>0)
					{
						$ar_all_binded_credit_project_id_ex	= array_unique($ar_all_binded_credit_project_id['content']);
					}
					
					# 排除已经被绑定过的信用项目id
					#
					$build_sql_where_for_search->appendWhereFilterContidion(" and id not in(".implode(',',$ar_all_binded_credit_project_id_ex).") and 1=?",1);
				}
            }

            # 
            #
            $ar = array();$this->m_cHelper->gfDbQuery()->select	
			(
				"
                    select 
                            *
                            ,(select department_name	from ".$this->m_cHelper->gfGetTableName(TableConsts::CY_DEPARTMENT_TABLE_NAME)	." where department_id=a.credit_project_business_department_id)				as department_name
                            ,(select client_name		from ".$this->m_cHelper->gfGetTableName(TableConsts::CY_CLIENT_BASIC_TABLE_NAME)." where client_id=a.credit_project_client_id)								as client_name 
                            ,(
                                select 
                                    delay_date_end		
                                from 
                                    ".$this->m_cHelper->gfGetTableNameByConstKey('CY_DELAY_DATE_TABLE_NAME')."	
                                where 
                                    pid		= a.id 
                                    and id	= (select ifnull(max(id),0) from ".$this->m_cHelper->gfGetTableNameByConstKey('CY_DELAY_DATE_TABLE_NAME')." where pid=a.id)
                            )																																														as credit_project_quota_date
                            ,(select staff_name			from ".$this->m_cHelper->gfGetTableName(TableConsts::CY_STAFF_TABLE_NAME)		." where staff_id=a.credit_project_business_staff_id)						as credit_project_business_staff_name
                            ,(select staff_name			from ".$this->m_cHelper->gfGetTableName(TableConsts::CY_STAFF_TABLE_NAME)		." where staff_id=a.credit_project_agent_staff_id)							as credit_project_agent_staff_name
                    from 
                            ".$this->m_cHelper->gfGetTableNameByConstKey('CY_CREDIT_PROJECT_EX_TABLE_NAME')."																										as a
                            force index (
                                            ".	(
                                                    ( 
														@$filters->credit_project_name				!= '' 
														||
														@$filters->bind_contract_to_credit_project	!= ''
													)
                                                    ?"primary"
                                                    :"credit_project_business_department_id"
                                                )
                                            ."
                                        )
                    where 
                            ".$build_sql_where_for_search->getAllCombineBuildStandarSQL()->sql_where."
                            and status	= 1
                            and 1		= ?
                    order by a.id desc
                "
                ,
                $build_sql_where_for_search->getAllCombineBuildStandarSQL()->thisx->merge([1])->getLastSingleArray()
                ,
                $j->page_size		# one page size
                ,
                $j->page			# page index => [ first = 1,second = 2 ... ]
                ,
                debug:false
            )
			->getPageOffsetInfo($ar)->forEachRow
			(
				function($row)
				{
					return	[
									'id'										=> $row->id													,
									'key'										=> $row->id													,
									'credit_project_approve_code'				=> $row->credit_project_approve_code						,	# 审批编号
									'credit_project_id'							=> $row->id													,	# 项目id
									'credit_project_name'						=> $row->credit_project_name								,	# 项目名称
									'credit_project_business_department_id'		=> $row->credit_project_business_department_id				,	# 部门id
									'credit_project_business_department_name'	=> $row->department_name									,	# 部门名称
									'credit_project_business_staff_id'			=> $row->credit_project_business_staff_id					,	# 负责人id
									'credit_project_business_staff_name'		=> $row->credit_project_business_staff_name					,	# 负责人名称
									'credit_project_agent_staff_id'				=> $row->credit_project_agent_staff_id						,	# 经办人ID
									'credit_project_agent_staff_name'			=> $row->credit_project_agent_staff_name					,	# 经办人
									'credit_project_client_id'					=> $row->credit_project_client_id							,	# 客户id
									'credit_project_client_name'				=> $row->client_name										,	# 客户名称	
									'credit_project_prepaid_sale_type'			=> $row->credit_project_prepaid_sale_type					,	# 预付/赊销 1预付特批 2赊销
									'credit_project_quota'						=> $row->credit_project_quota								,	# 信用额度
									'credit_project_quota_date'					=> $row->credit_project_quota_date							,	# 额度使用截止日期

									# 2020.10.27 如果信用项目 [cy_credit_project_ex.credit_project_completed_status == 2 信用项目的完成状态：1=没有完成 2=已经完成【项目截止时间到了，项目账款回款完成】] 
									#
									#
									'credit_project_status'						=> (
																						$row->credit_project_completed_status == 2				# 信用项目已经成功完结
																						? 10													# 返回 10 给前端表明项目处于完结状态 [这个仅仅用于状态显示]
																						: $row->credit_project_status						
																						
																				   )														,	# 状态
									
									#
									#
									'auth'										=> $this->verifyEveryRowDataOperationPermission($row)		,	# 校验信用项目每一行数据是否可以进行对应的操作
							];
				}
				,
				$ar
			)->formatPagingStyle($ar);
            
            return $ar;
        }

        /* 创建信用项目确认事项的财务信息	=> 创建确认事项的财务信息
         *
         */
        public function creditProjectAddFinanceInformation($j,$credit_project_id)
        {
			if($this->verifyCreditProjectIdExistEx($credit_project_id)===false)
            {
                return $this->m_cHelper->gfApiEchoExHttpException("信用项目id ：$credit_project_id 不存在","creditProjectAddFinanceInformation.100");
            }

            # 财务专员提交的所有财务信息
            #
            $credit_project_confirm_information_for_finance = $j->getAllJsonData();

            # 保存数据 => cy_credit_project_ex.credit_project_confirm_information_for_finance
            #
            #
            $this->m_cHelper->gfDbQuery()->updateByArrayWithWhere	(
                                                                        $this->m_cHelper->gfGetTableNameByConstKey('CY_CREDIT_PROJECT_EX_TABLE_NAME')
                                                                        ,
																		[
																			"where id=? and owner_id=?"
																			,
																			[$credit_project_id,$this->m_cHelper->gfGetCurrentStaffInfo()->staff_id]
																		]
                                                                        ,
																		[
																			'credit_project_confirm_information_for_finance'	=> $this->m_cHelper->gfJsonEncode($credit_project_confirm_information_for_finance),
                                                                        ]
                                                                    );

            #
            #
            $credit_project_confirm_information_for_finance['credit_project_id'] = $credit_project_id;

            #
            #		
            return [$credit_project_confirm_information_for_finance];
        }
        /* 修改确认事项的财务信息
         *
         */
        public function creditProjectModifyFinanceInformation($j,$credit_project_id)
        {
			# add system operation log
			#
			$this->m_modelSystemOperationLog->addSystemOperationLog('修改确认事项的财务信息',$credit_project_id,$j->getOriginJsonString());

			#
			#
            return $this->creditProjectAddFinanceInformation($j,$credit_project_id);
        }

        /* 删除信用项目
         *
         */
        public function CreditProjectDelete(int $credit_project_id)
        {
            # can be modify
            #
            $cb = $this->verifyCreditProjectCanBeModify($credit_project_id);if($cb->b_can_be_modify===false)
            {
                return $this->m_cHelper->gfApiEchoExHttpException($cb->message,'CreditProjectDelete.100');
            }
            
            # fake deletion => importance tips : update field status to 2 only
            #
            $this->m_cHelper->gfDbQuery()->delete("update ".$this->m_cHelper->gfGetTableNameByConstKey('CY_CREDIT_PROJECT_EX_TABLE_NAME')." set `status`=2 where id=? and owner_id=?",[$credit_project_id,$this->m_cHelper->gfGetCurrentStaffInfo()->staff_id]);

			# add system operation log
			#
			$this->m_modelSystemOperationLog->addSystemOperationLog('删除信用项目',$credit_project_id);

            return	[
                        'credit_project_id'=>$credit_project_id
                    ];
        }

        /* 获取确认事项的财务信息
         *
         */
        public function creditProjectGetFinanceInformation($credit_project_id)
        {
            #
            #
            if($this->m_cHelper->gfDbQuery()->getDbValue("select id from ".$this->m_cHelper->gfGetTableNameByConstKey('CY_CREDIT_PROJECT_EX_TABLE_NAME')." where status=1 and id=?",[$credit_project_id])>0)
            {
            }
            else
            {
                return $this->m_cHelper->gfApiEchoExHttpException("信用项目id ：$credit_project_id 不存在","creditProjectGetFinanceInformation.100");
            }

            #
            #
            $credit_project_confirm_information_for_finance = $this->m_cHelper->gfDbQuery()->getDbValue
			(
				"
                    select 
                            credit_project_confirm_information_for_finance 
                    from
                            ".$this->m_cHelper->gfGetTableNameByConstKey('CY_CREDIT_PROJECT_EX_TABLE_NAME')."
                    where
                            id=?"
                ,
				[$credit_project_id]
            );


            # 信用项目的确认事项之财务信息确认 (当申请被提交审查，需要保存财务确认信息到这来）tips:json
            #
            return $this->m_cHelper->gfJsonDecode($credit_project_confirm_information_for_finance)->getAllJsonData();
        }

        /* 获取关联部门信息
         * 
         * tips :	[部门和公司的统计功能暂时不要以后再说吧]
         * 
         *			1. 查询时间的基点默认就是当前时间
         *			2. 找出本部门( $department_id )在有效期内签订的全部预付合同 （同上游客户签订）和所有信用项目（下游客户的【赊销】，上游客户的【预付特批】）
         *
         * date	: 2022.06.01
         *
         *			1. 仅仅罗列本部门的所有项目信息由于部门签订项目包括（上游预付合同项目，下游赊销信用项目，上游预付特批项目）3 种情况分开处理
         *																																		
         *																																	+-------------------+	
         *																																	|部门的所有项目信息	|									
         *																																	+---+---------------+									
         *																																		|											+-------------------+
         *																													+-----------+		|							+-------------->| 信用项目			|-----------+
         *																													| 预付合同  |<------+---------------------------+	 			+-----------+-------+			|
         *																											+-------+-----------+																					|
         *																											|																										|
         *																											|																										|
         *																											|																										|
         *																											|																										|
         *																											|																										|
         *																											|							+---------------------------------------------------------------------------+	
         *																											|							|							|
         *																											|							|							|
         *																											|							|							|
         *																											|							|							|
         *																											|							|							|
         *																											V							V                  			V           
         *																									+-------+----------+		+-------+----------+		+-------+----------+
         *																									| 上游预付合同项目 |		| 上游预付特批项目 |		| 下游赊销信用项目 |
         *																									+------------------+		+------------------+		+------------------+
         * 
         */
        public function creditDetailGetRelationDepartmentInformation($department_id/* 部门id */)
        {
            # 获取部门基本信息
            #
            $ar_department_info = $this->m_cHelper->gfDbQuery()->getDbOneRow
			(
				"
                    select 
                            a.*
                            ,b.company_name
                    from 
                            ".$this->m_cHelper->gfGetTableNameByConstKey('CY_DEPARTMENT_TABLE_NAME')."	as a
                    left join
                            ".$this->m_cHelper->gfGetTableNameByConstKey('CY_COMPANY_TABLE_NAME')."		as b
                    on
                            a.company_id	= b.company_id
                    where  
                            a.department_id	= ?
                "
                ,[$department_id]
            );
            if(!$this->m_cHelper->gfIsPureInteger($department_id) ||count($ar_department_info)==0)
            {
                return $this->m_cHelper->gfApiEchoExHttpException('部门id='.$department_id.' 不存在','creditDetailGetRelationDepartmentInformation.100');
            }

            # 从当前部门查出所有预付合同关联的所有上游客户id
            #
            $this->m_cHelper->gfDbQuery()->select
			(
					"
						select 
								a.client_id												/* 上游客户id													*/
						from 
								".$this->m_cHelper->gfGetTableNameByConstKey('CY_CONTRACT_PREPAY_COLLECT_TABLE_NAME')."		as a 
						right join
								".$this->m_cHelper->gfGetTableNameByConstKey('CY_CONTRACT_TABLE_NAME')."					as b   
						on
								a.contract_id							= b.contract_id
						where
								1										= 1
								and b.responsible_department_id			= ?				/* 部门id														*/
								and b.status							= 1				/* 合同状态正常	【合同状态 1正常 2已删除】						*/		
								and a.status							= 1				/* 1正常 2历史													*/
								and b.contract_status in (10,11,12,14)					/* 正常的合同状态 [已签署 10 履约中 11 已归档 12 履约完成 14	*/
						group by
								a.client_id												/* 去重 client_id												*/
					"
					,[$department_id]
            )
			->forEachRow
			(
					function($row)
					{
						return $row->client_id;
					}
					,$ar_all_client_id_for_upstream
			);

            # 从当前部门查出信用项目关联的所有客户id 【 上游客户(1预付特批)和下游客户(2赊销)都有可能出现 】
            #
            $this->m_cHelper->gfDbQuery()->select 
			(
				"
                    select
                            a.credit_project_client_id						/* 客户id	【上下游客户id都有可能】				*/
                    from 
                            ".$this->m_cHelper->gfGetTableNameByConstKey('CY_CREDIT_PROJECT_EX_TABLE_NAME')."			as a
                    left join
                            ".$this->m_cHelper->gfGetTableNameByConstKey('CY_CLIENT_BASIC_TABLE_NAME')."				as b
                    on
                            a.credit_project_client_id=b.client_id
                    where
                            1											= 1
                            and a.credit_project_business_department_id	= ?	/* 部门id											*/
                            and a.status								= 1        
                    group by
                            a.credit_project_client_id						/* 去重												*/	
                "
                ,[$department_id]
            )
			->forEachRow
			(
				function($row)
				{
					return $row->credit_project_client_id;
				}
				,$ar_all_client_id_for_downsteam
			);
            
            # 合并所有的客户id并去掉重复
            #
            $ar_all_client_id				= array_unique(array_merge($ar_all_client_id_for_upstream['content'],$ar_all_client_id_for_downsteam['content']));
            $department_information_detail	= [];

            # 部门信用规模使用情况 （历史明细）
            # 
            #
            {
                foreach($ar_all_client_id as $one_client_id)
				{
                    #  获取每一个客户($one_client_id)的项目列表	+------> 下游客户 ----------- => 赊销信用项目
                    #											|
                    #											|
                    #											|
                    #											|					  +------ => 预付合同项目
                    #											|					 /	
                    #											+------> 上游客户 --<
                    #																 \
                    #																  +------ => 预付特批项目
                    #
                    #
                    #
                    #
                    $ar_one_client_all_projects = $this->getCreditClientAllProject($one_client_id,true/* 查看全部项目 */)['content'];if(count($ar_one_client_all_projects)==0)
					{
					}
					else
					{
                        # 成功获取客户($one_client_id)的所有项目
                        #
                        foreach($ar_one_client_all_projects as $one_project)
						{
                            $o									= (object)$one_project;
                            $department_information_detail	[]	= [
                                                                    'client_name'						=> $o->credit_project_client_name					,
                                                                    'client_id'							=> $o->credit_project_client_id						,
                                                                    'credit_project_quota'				=> (
                                                                                                                    $o->credit_project_prepaid_sale_type == 2	/* 1=预付特批 2=赊销																				*/ 
                                                                                                                    ?$o->credit_project_quota_sale				/* 赊销																								*/
                                                                                                                    :$o->credit_project_quota_prepaid			/* [prepaid_type=100] => 预付 [prepaid_type=200] => 预付特批										*/
																											)												,	/* 信用项目额度																						*/		
                                                                    'credit_project_quota_current'		=> 0												,	/* 不计算，保持为 0																					*/
                                                                    'credit_project_quata_end_time'		=> $o->credit_project_quota_date					,	/* 信用项目截止日期																					*/
                                                                    'credit_project_status'				=> $o->credit_project_status						,	/* 信用项目的状态：1=等待审核 2=审核完成 3=[信控专员审查] 4=[财务专员审查] 5=审核中 6=审核不通过	*/
                                                                    'credit_project_id'					=> $o->credit_project_id							,
                                                                    'credit_project_name'				=> $o->credit_project_name							,
                                                                    'credit_project_prepaid_sale_type'	=> $o->credit_project_prepaid_sale_type				,	/* 1=预付特批 2=赊销																				*/ 
                                                                    'credit_project_approve_code'		=> $o->credit_project_approve_code					,	/* 审批编号																							*/
                                                                    'prepaid_type'						=> $o->prepaid_type									,	/* 100=>预付合同项目 200=>预付特批项目 -1=>信用项目中的赊销项目										*/
                                                                    'credit_project_completed_status'	=> (
                                                                                                                @$o->credit_project_completed_status > 0				
                                                                                                                ?$o->credit_project_completed_status
                                                                                                                :0
																											)												,	/* 信用项目的完成状态：1=没有完成 2=已经完成【项目截止时间到了，项目账款回款完成】					*/
                                                                    ];
                        }
                    }
                }
            }

            return	[
                        # 部门信息
                        #
                        'department_information'		=>	[
                                                                'department_id'							=>	$ar_department_info['department_id']	,									
                                                                'department_name'						=>	$ar_department_info['department_name']	,									
                                                                'department_amount_max'					=>	0										,
                                                                'department_amount_remain'				=>	0										,
                                                                'company_name'							=>	$ar_department_info['company_name']		,									
                                                                'company_amount_max'					=>	0										,
                                                                'company_amount_remain'					=>	0										,
                                                            ],
                        # 部门产生的所有项目明细
                        #
                        'department_information_detail'	=> $department_information_detail,
                    ];
        }

        public function getSimpleProjectInfoByCreditProjectId(int $credit_project_id,$selectStr = "*")
		{
           return $this->m_cHelper->gfDbQuery()->getDbOneRow("

                    select 
                            ".$selectStr."
                    from
                            ".$this->getTableName()."
                    where
                            id=?"
                ,
                [$credit_project_id]
            );
        }

        public function editSimpleCreditProjectByCreditProjectId($creditProjectData)
		{
            return $this->where('id',$creditProjectData['id'])->update($creditProjectData);
        }

        /* 获取关联合同信息
         *
         */
        public function creditDetailGetRelationContractInformation($credit_project_id)
		{
            # 项目项目存在吗 ?
            #
            if($this->verifyCreditProjectIdExistEx($credit_project_id)===false)
			{                
                return $this->m_cHelper->gfApiEchoExHttpException("信用项目: ".$credit_project_id." 不存在","creditDetailGetRelationContractInformation.100");	# panic => fatal error
            }

            # 从当前信用项目【项目类型可能为：1 赊销（下游客户产生） ，2 预付特批（上游客户产生）】从绑定表【 cy_contract_credit_project 】反向找关联的合同
            #
            #
            $this->m_cHelper->gfDbQuery()->select
			(
				"
                    select
                            /* 信用项目的额度
                             *
                             */
                            c.credit_project_quota

                            /* 关联信用项目的类型【赊销或预付特批】
                             *
                             */
                            ,c.credit_project_prepaid_sale_type
                            ,if(
                                    c.credit_project_prepaid_sale_type=1/* 预付/赊销 1预付特批 2赊销   */
                                    ,'".$this->m_cHelper->getDictionaryInfoByDictionaryKeyEx('credit_project_prepaid')	->dictionary_name."'
                                    ,'".$this->m_cHelper->getDictionaryInfoByDictionaryKeyEx('credit_project_sale_type')->dictionary_name."'
                            )																																		as credit_project_prepaid_sale_type_name

                            ,b.contract_id

                            /* 合同状态 => 待信控法务审批=1 信控送审中=2 法务送审中=3 信控送审未通过=4 法务送审未通过=5 待送审=6 送审中=7 已退回=8 待送签=9 已签署=10 履约中=11 已归档=12		
                             *
                             */
                            ,b.contract_status																																							
                            ,(
                                select 
                                        dictionary_name 
                                from 
                                        ".$this->m_cHelper->gfGetTableNameByConstKey('CY_DATA_DICTIONARY_TABLE_NAME')."												force index(parent_id)
                                where 
                                        parent_id				= 100
										and status				= 1
                                        and dictionary_value	= b.contract_status																					
                            )																																		as contract_status_name				/* 合同状态											*/
                            
                            /* 合同类型
                             *
                             */
                            ,(
                                select 
                                        contract_type_name 
                                from 
                                        ".$this->m_cHelper->gfGetTableNameByConstKey('CY_CONTRACT_TYPE_TABLE_NAME')."												
                                where 
                                        contract_type_id=b.contract_type_id
                            )																																		as contract_type_name				/* 合同类型											*/
                            
                            
                    from
                            ".$this->m_cHelper->gfGetTableNameByConstKey('CY_CONTRACT_CREDIT_PROJECT_TABLE_NAME')."													as a force index(credit_project_id)	/* 合同项目关联表									*/
                    left join
                            ".$this->m_cHelper->gfGetTableNameByConstKey('CY_CONTRACT_TABLE_NAME')."																as b								/* 合同表											*/
                    on
                            a.contract_id			= b.contract_id
                    left join
                            ".$this->m_cHelper->gfGetTableNameByConstKey('CY_CREDIT_PROJECT_EX_TABLE_NAME')."														as c								/* 信用项目表										*/
                    on	
                            a.credit_project_id		= c.id
                    where
                            1						= 1
                            and b.status			= 1
                            and c.status			= 1
                            and a.credit_project_id	= ?
                "
                ,
				[$credit_project_id]
            )
			->forEachRow
			(
							function($row)
							{
								return $row->appendItem((new ContractService())->getNewestContractDetailByContractId($row->contract_id)/* 获取合同具体信息 */)->getOneRowAllData();
							}
							,
							$relation_contract_information
			);
			
			#
			#
            return ['relation_contract_information' => $relation_contract_information['content']];
        }


		/* 返回信用项目处于审查中的状态值  
		 *
		 */
		private function getCreditProjectStatusInReviwing()
		{
			$ar=	[
						self::CREDIT_PROJECT_STATUS_8_DEPARTMENT_LEADER_REVIEWING		# 部门领导初步审查
						,
						self::CREDIT_PROJECT_STATUS_3_CREDIT_MANAGER_REVIEW				# 信控专员审查
						,
						self::CREDIT_PROJECT_STATUS_4_FINANCE_MANAGER_REVIEW			# 财务专员审查
						,
						self::CREDIT_PROJECT_STATUS_5_REVIEWING							# 审核中 [ 丁丁领导审查 ]
						,
						self::CREDIT_PROJECT_STATUS_9_FINANCE_MANAGER_REVIEW_COMPLETED	# 财务专员审查已经完成
					];
			return	(
						new class($ar)
						{
							public function __construct($ar)
							{
								$this->m_ar = $ar;
							}
							public function toArray()
							{
								return $this->m_ar;
							}
							public function toString()
							{
								return implode(',',$this->m_ar);
							}
						}
					);
		}










    }